package com.ruoyi.utli;


import com.ruoyi.base.mapper.PublicToolsMapper;
import com.ruoyi.common.utils.BankerSRoundingUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.js.Standard;
import com.ruoyi.system.domain.SysConfig;
import com.ruoyi.system.mapper.SysConfigMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Component
public class SegmentFormula {
    @Autowired
    private PublicToolsMapper publicToolsMapper;
    @Autowired
    private SysConfigMapper sysConfigMapper;

    /**
     * @return java.lang.Double
     * @Description 根据传入的值进行截取(最后一位不能为0倒数第二位值要是0 ， 保留最后一位有效值)
     * @Param [datastring]
     **/
    public static Double ConvertData(Double datastring) {
        DecimalFormat decimalFormat = new DecimalFormat("#.################");
        String datas = decimalFormat.format(datastring);
        boolean contains = datas.contains(".");//是否存在小数点
        if (contains) {
            int index = datas.indexOf(".");//获取小数点前的数据位数
            String beforeNum = datas.substring(index + 1, datas.length());//进行截取小数点后的数据
            int k = 0;//存放有效数据的位置
            for (int i = 0; i < beforeNum.length(); i++) {
                char c = beforeNum.charAt(i);//获取当前值
                String aDouble = String.valueOf(c);//转换进行判断

                //判断数据不能为0，如果为0结束循环返回值
                if (!"0".equals(aDouble)) {
                    break;
                }
                k++;//如果不为0加一



            }
            //判断是否科学计算法，如果是就进行转换
            boolean scientificNotation = StringUtils.isScientificNotation(String.valueOf(datastring));
            if (scientificNotation) {
                BigDecimal bigDecimal = new BigDecimal(String.valueOf(datastring));
                String effectiveValuesdatas = bigDecimal.toPlainString();
                datastring = Double.valueOf(effectiveValuesdatas);
            } else {
                if(datastring!=null&&!"--".equals(datastring)&&!"-1".equals(datastring)&&!"*".equals(datastring)&&!"".equals(datastring)){
                    datastring=Double.valueOf(String.valueOf(datastring));
                }
            }
            String data = BankerSRoundingUtils.sciCal(datastring, k+1);
            return Double.valueOf(data);
        }
        return null;
    }

    /**
     * 单因子的营养tel
     * @Param [itemcode, itemData]
     * @return java.lang.String
     **/
    public  String nutrientWaterQualityIndexitemtel(String itemcode, String itemData) {
        Map map = new HashMap();
        String WaterQualityIndex=null;
        if(itemcode!=null&&"48F20E91-9571-436D-8D87-4DCCFEFF30C0".equals(itemcode)){
            double v = Double.valueOf(itemData) * 1000;
            itemData=String.valueOf(v);
            double v1 = (10*(2.5 + 1.086 * Math.log(Double.valueOf(itemData))));
            System.out.println(v1);
            if (!Double.isNaN(v1)){
                WaterQualityIndex=String.valueOf(v1);
            }
            map.put("waterQualityIndex",v1);
        }
        // TLI（SD）=10（5.118-1.94*ln(因子均值)）透明的
        if(itemcode!=null&&"CC71B6B7-3A17-4606-B9C7-3FD54217984D".equals(itemcode)){
            double v = Double.valueOf(itemData) / 100;
            itemData=String.valueOf(v);
            double v1 = (10*(5.118 + 1.94 * Math.log(Double.valueOf(itemData))));
            System.out.println(v1);
            if (!Double.isNaN(v1)){
                WaterQualityIndex=String.valueOf(v1);
            }
            map.put("waterQualityIndex",v1);
        }
        // TLI（TP）=10（9.436+1.624*ln(因子均值)） 总磷
        if(itemcode!=null&&"7441BE61-F30B-4FCB-B2C5-8EE2F0AE99D2".equals(itemcode)){
            //double v = Double.valueOf(itemData) * 100;
            //itemData=String.valueOf(v);
            double v1 = (10*(9.436 +1.624 * Math.log(Double.valueOf(itemData))));
            System.out.println(v1);
            if (!Double.isNaN(v1)){
                WaterQualityIndex=String.valueOf(v1);
            }
            map.put("waterQualityIndex",v1);
        }
        // TLI（TN ）=10（5.453+1.694*ln(因子均值)）总氮
        if(itemcode!=null&&"6F2E428C-2705-4DC1-A1D8-235CB9330593".equals(itemcode)){
            // double v = Double.valueOf(itemData) * 100;
            // itemData=String.valueOf(v);
            double v1 = (10*(5.453 +1.694 * Math.log(Double.valueOf(itemData))));
            System.out.println(v1);
            if (!Double.isNaN(v1)){
                WaterQualityIndex=String.valueOf(v1);
            }
            map.put("waterQualityIndex",v1);
        }
        // TLI（CODMn）=10（0.109+2.661*ln(因子均值)）高锰酸盐指数
        if(itemcode!=null&&"B78CC0BE-EE77-472F-9F02-C4CA86116F72".equals(itemcode)){
            //double v = Double.valueOf(itemData) * 100;
            //itemData=String.valueOf(v);
            double v1 = (10*(0.109 +2.661 * Math.log(Double.valueOf(itemData))));
            System.out.println(v1);
            if (!Double.isNaN(v1)){
                WaterQualityIndex=String.valueOf(v1);
            }
            map.put("waterQualityIndex",v1);
        }

        return WaterQualityIndex;
    }

    /**
     * 单个因子营养水质指数
     * @Param [itemcode, itemData]
     * @return java.util.Map<java.lang.String,java.lang.Object>
     **/
    public  String nutrientWaterQualityIndexitem(String itemcode, String itemData) {
        Map map = new HashMap();
        //根据公式进行计算不同因子营养水质指数
        //TLI（chl）=10（2.5+1.086*ln(因子均值)） 叶绿素
        String WaterQualityIndex=null;
        if(itemcode!=null&&"48F20E91-9571-436D-8D87-4DCCFEFF30C0".equals(itemcode)){
            double v = Double.valueOf(itemData) * 1000;
            itemData=String.valueOf(v);
            double v1 = (10*(2.5 + 1.086 * Math.log(Double.valueOf(itemData)))*(1/3.7558));
            System.out.println(v1);
            if (!Double.isNaN(v1)){
                WaterQualityIndex=String.valueOf(v1);
            }
            map.put("waterQualityIndex",v1);
        }
        // TLI（SD）=10（5.118-1.94*ln(因子均值)）透明的
        if(itemcode!=null&&"CC71B6B7-3A17-4606-B9C7-3FD54217984D".equals(itemcode)){
            double v = Double.valueOf(itemData) / 100;
            itemData=String.valueOf(v);
            double v1 = (10*(5.118 + 1.94 * Math.log(Double.valueOf(itemData)))*(0.6889/3.7558));
            System.out.println(v1);
            if (!Double.isNaN(v1)){
                WaterQualityIndex=String.valueOf(v1);
            }
            map.put("waterQualityIndex",v1);
        }
        // TLI（TP）=10（9.436+1.624*ln(因子均值)） 总磷
        if(itemcode!=null&&"7441BE61-F30B-4FCB-B2C5-8EE2F0AE99D2".equals(itemcode)){
            //double v = Double.valueOf(itemData) * 100;
            //itemData=String.valueOf(v);
            double v1 = (10*(9.436 +1.624 * Math.log(Double.valueOf(itemData)))*(0.7056/3.7558));
            System.out.println(v1);
            if (!Double.isNaN(v1)){
                WaterQualityIndex=String.valueOf(v1);
            }
            map.put("waterQualityIndex",v1);
        }
        // TLI（TN ）=10（5.453+1.694*ln(因子均值)）总氮
        if(itemcode!=null&&"6F2E428C-2705-4DC1-A1D8-235CB9330593".equals(itemcode)){
            // double v = Double.valueOf(itemData) * 100;
            // itemData=String.valueOf(v);
            double v1 = (10*(5.453 +1.694 * Math.log(Double.valueOf(itemData)))*(0.6724/3.7558));
            System.out.println(v1);
            if (!Double.isNaN(v1)){
                WaterQualityIndex=String.valueOf(v1);
            }
            map.put("waterQualityIndex",v1);
        }
        // TLI（CODMn）=10（0.109+2.661*ln(因子均值)）高锰酸盐指数
        if(itemcode!=null&&"B78CC0BE-EE77-472F-9F02-C4CA86116F72".equals(itemcode)){
            //double v = Double.valueOf(itemData) * 100;
            //itemData=String.valueOf(v);
            double v1 = (10*(0.109 +2.661 * Math.log(Double.valueOf(itemData)))*(0.6889/3.7558));
            System.out.println(v1);
            if (!Double.isNaN(v1)){
                WaterQualityIndex=String.valueOf(v1);
            }
            map.put("waterQualityIndex",v1);
        }
        if(WaterQualityIndex!=null&&!"".equals(WaterQualityIndex)){
            Boolean doublecl = StringUtils.Doublecl(Double.valueOf(WaterQualityIndex));
            if(doublecl){

            }else {
                WaterQualityIndex=null;
            }
        }

        return WaterQualityIndex;
    }

    /**
     * @return java.lang.String
     * 河流水质指数
     * @Param [datastring 所有因子水质指数]
     **/
    public String riverWaterQualityIndex(List<String> datastring) {
        Double datalist = null;
        for (String data:datastring){
            if(data!=null&&!"".equals(data)&&!"null".equals(data)){
                Double dataDouble = Double.valueOf(data);//获取单个因子转换为可计算的数据格式
                //判断存放值不能为空，为空直接赋值，不为空就进行相加
                if(datalist!=null){
                    datalist = datalist + dataDouble;
                } else {
                    datalist = dataDouble;
                }
            }


        }
        //进行四舍六入五成双
        String data = BankerSRoundingUtils.sciCal(datalist, 4);
        return data;
    }

    /**
     * 湖泊（水库）营养状态分级
     * @Param [itemData]
     * @return java.lang.String
     **/
    public  String nutrientWaterQualityIndexclassification(Double itemData) {
        //采用0～100的一系列连续数字对湖泊（水库）营养状态进行分级：
        String WaterQualityIndex=null;
        // TLI （∑）＜30 贫营养（ Oligotropher）
        if(itemData>=0&&itemData<30){
            WaterQualityIndex="贫营养";
        }
        // 30≤TLI （∑）≤50 中营养（ Mesotropher）
        else if(30<=itemData&itemData<=50){
            WaterQualityIndex="中营养";
        }
//TLI （∑）>50 富营养 (Eutropher)
        else if(itemData>50){
            WaterQualityIndex="富营养";
        }
        //50＜TLI （∑）≤60 轻度富营养 (light eutropher)
        else if(50<itemData&itemData<=60){
            WaterQualityIndex="轻度富营养";
        }
        //60＜TLI （∑）≤70 中度富营养 (Middle eutropher)
        else if(60<itemData&itemData<=70){
            WaterQualityIndex="中度富营养";
        }
        //TLI （∑）>70 重度富营养 (Hyper eutropher)
        else if(itemData>70){
            WaterQualityIndex="重度富营养";
        }
        //在同一营养状态下，指数值越高，其营养程度越重。
        return WaterQualityIndex;
    }

    /**
     * 手工数据导入根据因子返回对应状态
     * @Param [value 监测值, ItemCode 因子编码,itemName 因子名称 type 数据类型]
     **/
    public String ItemCodestate(Double value, String ItemCode, String itemName, String type) {
        String ItemState = null;//返回因子状态
        //传参数据
        Map map = new HashMap();
        map.put("ItemCode", ItemCode);//因子id
        map.put("ItemName", itemName);//因子名称
        map.put("bussinessCategoryCode", type);//数据类型
        map.put("id", ItemCode);//查询因子基础表参数
        //返回因子基本信息
        Map wqBasItemID = publicToolsMapper.wqBasItemID(map);
        //查询因子基本信息是否存在不存在直接返回状态
        if (wqBasItemID != null && wqBasItemID.size() > 0) {
            //根据因子id和数据类型查询对应因子的上下限
            List<Map> wqcodbussinessitemsNamelist = publicToolsMapper.wqcodbussinessitemsName(map);
            if (wqcodbussinessitemsNamelist != null && wqcodbussinessitemsNamelist.size() > 0) {
                Object maxValue = wqcodbussinessitemsNamelist.get(0).get("MaxValue");//上限
                Object minValue = wqcodbussinessitemsNamelist.get(0).get("MinValue");//下限
                //判断对应上下限是否存在不存在返回正常，存在就判断是否在上下限中，如果超过就返回超出范围
                if (maxValue != null && !"".equals(maxValue)) {
                    Double maxValueDouble = Double.valueOf(String.valueOf(maxValue));
                    if (value > maxValueDouble) {
                        //超出范围
                        ItemState = "2";
                        return ItemState;
                    }

                } else if (minValue != null && !"".equals(minValue)) {
                    Double minValueDouble = Double.valueOf(String.valueOf(minValue));
                    if (value < minValueDouble) {
                        //超出范围
                        ItemState = "2";
                        return ItemState;
                    }
                }

            } else {
                //该项在该业务中不存在
                ItemState = "2";
                return ItemState;
            }
        } else {
            //监测项不存在
            ItemState = "6";
            return ItemState;
        }
        //默认数据正常
        ItemState = "0";
        return ItemState;

    }

    /**
     * 水质趋势评价
     *  获取环比的水质等级，然后跟当天的比较
     * @Param [quality 当前水质级别, lastQualitylevel]环比水质级别
     * @return java.util.Map<java.lang.String,java.lang.Object>
     **/
    public Map<String, Object> evaluationTrend(Integer quality,Integer lastQualitylevel) {
        Map map = new HashMap();
        if(quality!=null&&quality>0 && lastQualitylevel>0){
            if (StringUtils.isNotNull(quality)) {
                //计算相差几个等级
                int nums = quality - lastQualitylevel;
                if (nums == 0) {
                    map.put("evaluationTrendCode","1");
                    map.put("evaluationTrend","无明显变化");
                } else if (nums == 1 || nums == -1) {
                    map.put("evaluationTrendCode","2");
                    if (quality > lastQualitylevel) {
                        map.put("evaluationTrend","有所变差");
                    } else if (quality < lastQualitylevel) {
                        map.put("evaluationTrend","有所变好");
                    }
                } else {
                    map.put("evaluationTrendCode","3");
                    if (quality > lastQualitylevel) {
                        map.put("evaluationTrend","有所下降");
                    } else if (quality < lastQualitylevel) {
                        map.put("evaluationTrend","有所变好");
                    }
                }
            }
        }

        return map;
    }

    /**
     * 根据断面类型和水质等级，获取对应因子标准值
     * @Param [type 断面类型, Level 水质等级]
     **/
    public List<Map<String, Object>> wqBasStandardcategory(String type, String Level) {
        //获取对应断面的标准值
        Map wqBasStandardcategorymap = new HashMap();
        wqBasStandardcategorymap.put("type", type);
        wqBasStandardcategorymap.put("Level", Level);
        List<Map<String, Object>> maps = publicToolsMapper.wqBasStandardcategorylist(wqBasStandardcategorymap);
        return maps;
    }

    /**
     *查询水质指数和修约后的值
     * @Param [indexstandardLimits 计算水质指数的标准值  roundingOffstandardLimits 计算均值修约的数据 itemName 监测值名称, type 断面类型, beginTime 开始时间, endTime 结束时间, itemdata 监测值]
     **/
    public Map itemDataINV(String indexstandardLimits, String roundingOffstandardLimits, String itemCode, String itemName, String type, String beginTime, String endTime, String itemdata) {
        //查询是否修约
        SysConfig sysConfig=new SysConfig();
        List<SysConfig> sysConfigs = sysConfigMapper.selectConfigList(sysConfig);
        String indexSegment=null;//断面是否修约
        if(sysConfigs!=null&&sysConfigs.size()>0){
            for(SysConfig data:sysConfigs){
                String configKey = data.getConfigKey();
                String configValue = data.getConfigValue();
                if(configKey.equals("index.segment")){
                    indexSegment=configValue;
                }
            }

        }
        //调用工具类判断是否需要/2
        itemdata = this.verificationOfMonitoringValues(itemdata);
        Map<String, Object> maplistData = new HashMap<>();//存放断面处理过的数据值
        //判断导入监测只是否为空和-1
        if (itemdata != null && !"".equals(itemdata) && !"-1".equals(itemdata)) {
            //在计算水质指数之前先把平均值进行修约
            String jzaDouble1 = this.roundingOffs(Double.valueOf(itemdata), itemCode, String.valueOf(roundingOffstandardLimits), 0.0, "1", "", "");
            String aDouble1 =null;
            if(indexSegment!=null&&"0".equals(indexSegment)){
                aDouble1 = this.roundingOffs(Double.valueOf(itemdata), itemCode, String.valueOf(roundingOffstandardLimits), 0.0, "1", "", "");

            }else {
                aDouble1=itemdata;
            }
            String aDouble = this.waterQualityIndexOfIndividualIndicatorss(Double.valueOf(aDouble1), itemCode, Double.valueOf(roundingOffstandardLimits), Double.valueOf(indexstandardLimits), type, beginTime, endTime, "1");
            Map mapdat = new HashMap();
            mapdat.put("ItemCode", itemCode);
            mapdat.put("bussinessCategoryCode", "CBN");
            maplistData.put("_V", jzaDouble1);
            maplistData.put("_IN", aDouble);
            maplistData.put("itemCode", itemCode);
        } else {
            maplistData.put("_V", null);
            maplistData.put("_IN", null);
            maplistData.put("itemCode", itemCode);
        }
        return maplistData;
    }

    /**
     * 根据传入string类型监测值进行判断是否带特殊符合l L - <= <
     **/
    public static String verificationOfMonitoringValues(String itemdata) {
        if (itemdata != null && !"".equals(itemdata)) {
            boolean itemvalue = checkSpecialChars(itemdata);
            if (itemvalue) {
                // 使用正则表达式去除特殊符号
                String result = itemdata.replaceAll("[lL<=<-]", "");
                Double aDouble = Double.valueOf(result);
                BigDecimal aDoubleBigDecimal = new BigDecimal(Double.toString(aDouble));
                BigDecimal divide = aDoubleBigDecimal.divide(new BigDecimal(2.0));
                return String.valueOf(divide);
            } else {
                return itemdata;
            }
        } else {
            return itemdata;
        }

    }
    //判断是否存在指定特殊负号
    public static boolean checkSpecialChars(String specialChars) {
        String regex = "[" + Pattern.quote(specialChars) + "]";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher("lL-<=<");

        return matcher.find();
    }

    /**
     * 平均值进行修约计算（传入前监测值不能为0）
     * @Param [value 需要计算的监测值, ItemCode 监测因子id,standardValue一类水标准 修约数据  standardLimits 三类水标准上下限  , type 标准类型 1河流 2湖库 3地下水 , beginTime 开始时间 ,endTime 结束时间 ]
     **/
    public String roundingOffs(Double value, String ItemCode, String standardValue, Double standardLimits, String type, String beginTime, String endTime) {
        DecimalFormat decimalFormat = new DecimalFormat("#.################################################");
        String formattedNumber = decimalFormat.format(value);
        value = Double.parseDouble(formattedNumber);
        //standardValue = decimalFormat.format(Double.valueOf(standardValue));
        //判断监测值如果为空就直接返回
        if (value == null) {
            return null;
        }
        //存放参数进行返回
        Double reValue = null;
        //如果标准值为空的话直接默认保留一位小数然后进行四舍六入五成双
        if (standardValue == null && "".equals(standardValue)) {
            String data = BankerSRoundingUtils.sciCal(value, 1);
            reValue = Double.valueOf(data);
        }
        //如果标准值不为空的话逻辑如下
        else {
            //获取因子需要保留的小数位计算 标准值位数+1
            String standardValueData = String.valueOf(standardValue);
            //获取小数位后的长度
            Integer standardValueint = standardValueData.length() - standardValueData.indexOf(".") - 1;
            Integer digit = standardValue.contains(".") ? standardValueint + 1 : 1;
            String data = BankerSRoundingUtils.sciCal(value, digit);
            reValue = Double.valueOf(data);
        }
        if (reValue == null) {
            //最后一位为0 获取监测值多取一位有效值
            //监测值转换为string类型进行截取
            String datas = String.valueOf(value);
            //转换后的监测值进行判读是否有小数位
            boolean contains = datas.contains(".");
            if (contains) {
                Double aDouble = ConvertData(value);//存在有小数才进行截取有效值
                //四舍 保留最后获取小数点后的位数
                String data = BankerSRoundingUtils.sciCal(aDouble, String.valueOf(aDouble).length());
                reValue = Double.valueOf(data);
            } else {
                reValue = value;
            }

        }
        if (reValue != null && !"".equals(reValue) && reValue == 0.0) {
            Double aDouble = ConvertData(value);
            String data = decimalFormat.format(aDouble);
            return data;
        }
        String data = decimalFormat.format(reValue);
        return data;

    }

    /**
     * 单项指标的水质指数
     * @Param [value 需要计算的监测值, ItemCode 监测因子id,roundingOffstandardLimits 一类水标准值用于修约 standardLimits 三类水标准上下限  , type 标准类型 1河流 2湖库 3地下水 , beginTime 开始时间 ,endTime 结束时间 ,roundingOff 是否修约 0修约 1不修约]
     **/
    public String waterQualityIndexOfIndividualIndicatorss(Double value, String ItemCode, Double roundingOffstandardLimits, Double standardLimits, String type, String beginTime, String endTime, String roundingOff) {
        String datalist = null;//每个因子水质指数计算后的值
        //ph需要单独计算 ph按照国家GB3838-2002标准 上限是9 下限是6
        if (ItemCode.equals("15DE941F-A221-4D9C-8387-48B0E99F6E25")) {
            //如果 pH≤7 时，计算公式为：
            /*   7.0-ph值/7.0-ph下限值     */
            if (value <= 7.0) {
                Double phdata = 7.0 - value;//ph计算值
                Double phstandardLimits = 7.0 - 6.0;//ph限制
                //double finalph = phdata / phstandardLimits;//计算后的最终值
                BigDecimal aDoubleBigDecimal = new BigDecimal(Double.toString(phdata));
                BigDecimal standardLimitsBigDecimal = new BigDecimal(Double.toString(phstandardLimits));
                //divide
                BigDecimal BigDecimaldata = aDoubleBigDecimal.divide(standardLimitsBigDecimal, 10, BigDecimal.ROUND_HALF_UP);
                datalist = BigDecimaldata.stripTrailingZeros().toPlainString();
            } else if (value > 7.0) {
                // ph值-7.0/ph上限值-7.0
                Double phdata = value - 7.0;//ph计算值
                Double phstandardLimits = 9.0 - 7.0;//ph限制
                BigDecimal aDoubleBigDecimal = new BigDecimal(Double.toString(phdata));
                BigDecimal standardLimitsBigDecimal = new BigDecimal(Double.toString(phstandardLimits));
                BigDecimal BigDecimaldata = aDoubleBigDecimal.divide(standardLimitsBigDecimal, 10, BigDecimal.ROUND_HALF_UP);
                datalist = BigDecimaldata.stripTrailingZeros().toPlainString();
            }
            //化学
        } else if (ItemCode.equals("CF745239-4FBE-46FF-ADA6-5B40FFBB1636")) {
            //获取到平均值之后按照规则进行修约
            String aDouble;
            if (roundingOff.equals("0")) {
                aDouble = roundingOffs(value, ItemCode, String.valueOf(roundingOffstandardLimits), standardLimits, type, beginTime, endTime);
            } else {
                aDouble = String.valueOf(value);
            }
            // 溶解氧的地表水Ⅲ类标准限值/溶解氧的浓度值
            BigDecimal aDoubleBigDecimal = new BigDecimal(aDouble);
            BigDecimal standardLimitsBigDecimal = new BigDecimal(Double.toString(standardLimits));
            BigDecimal BigDecimaldata = standardLimitsBigDecimal.divide(aDoubleBigDecimal, 10, BigDecimal.ROUND_HALF_UP);
            datalist = BigDecimaldata.stripTrailingZeros().toPlainString();

        } else {
            //获取到平均值之后按照规则进行修约
            String aDouble;
            aDouble = String.valueOf(value);
            //其他因子计算根据 浓度值/三类水标准值
            BigDecimal aDoubleBigDecimal = new BigDecimal(aDouble);
            BigDecimal standardLimitsBigDecimal = new BigDecimal(Double.toString(standardLimits));
            BigDecimal BigDecimaldata = aDoubleBigDecimal.divide(standardLimitsBigDecimal, 30, BigDecimal.ROUND_HALF_UP);
            datalist = BigDecimaldata.stripTrailingZeros().toPlainString();
        }

        return datalist;
    }

    /**
     * 水质评价结果
     * @Param [quality] 水质级别
     **/
    public Map<String, Object> waterQuality(Integer quality) {
        Map map = new HashMap();
        String waterQuality = "";
        String waterQualityColor = "";
        if (quality <= 2 && quality > 0) {
            waterQuality = "优";
            waterQualityColor = "蓝色";
        } else if (quality == 3) {
            waterQuality = "良好";
            waterQualityColor = "绿色";
        } else if (quality == 4) {
            waterQuality = "轻度污染";
            waterQualityColor = "黄色";
        } else if (quality == 5) {
            waterQuality = "中度污染";
            waterQualityColor = "橙色";
        } else if (quality == 6) {
            waterQuality = "重度污染";
            waterQualityColor = "红色";
        }
        map.put("waterQuality", waterQuality);
        map.put("waterQualityColor", waterQualityColor);

        return map;
    }


    /**
     * 根据传入的数据进行河流/湖库数据分组
     **/
    public Map<String, Object> Segmenfenzu(List<Map<String, Object>> maplist) {
        Map<String, Object> map = new HashMap<>();
        List<String> hlsegmeid = new ArrayList<>();
        List<String> hksegmeid = new ArrayList<>();
        List<String> dxsegmeid = new ArrayList<>();
        List<String> Countylist = new ArrayList<>();
        List<String> alllist = new ArrayList<>();
        List<Map<String, Object>> segmedata = new ArrayList<>();
        List<Map<String, Object>> hksegmedata = new ArrayList<>();
        if (maplist != null && maplist.size() > 0) {
            for (Map<String, Object> data : maplist) {
                Map<String, Object> hlmapdata = new HashMap<>();
                Map<String, Object> hkmapdata = new HashMap<>();
                Object id = data.get("SegmentID");//断面id
                Object County = data.get("County");//区划名称
                Object CountyCode = data.get("CountyCode");//区划编码
                Object IsDrink = data.get("IsDrink");//区划编码
                Object segmentCategory = data.get("SegmentCategory");//断面分类（1河流/2湖库/3地下水）
                if (segmentCategory != null && !"".equals(segmentCategory)) {
                    if (String.valueOf(segmentCategory).equals("1")) {
                        boolean contains = hlsegmeid.contains(id);
                        if (contains) {

                        } else {
                            hlsegmeid.add(String.valueOf(id));
                        }

                    }
                    if (String.valueOf(segmentCategory).equals("2")) {
                        boolean contains = hksegmeid.contains(id);
                        if (contains) {

                        } else {
                            hksegmeid.add(String.valueOf(id));
                        }
                        //hksegmeid.add(String.valueOf(id));

                    }
                    if (String.valueOf(IsDrink).equals("1")) {
                        boolean contains = dxsegmeid.contains(id);
                        if (contains) {

                        } else {
                            dxsegmeid.add(String.valueOf(id));
                        }

                    }
                }
                data.get("SegmentName");
                data.get("RiverName");
                data.get("RiverID");
                data.get("LakeName");
                data.get("LakeID");
                Object countyCode = data.get("CountyCode");
                data.get("County");
                data.get("SegmentCategory");
                data.get("TargetLevel");
                data.get("TargetLevelName");
                boolean contains = Countylist.contains(countyCode);
                boolean alllists = alllist.contains(id);
                if (alllists) {

                } else {
                    alllist.add(String.valueOf(id));
                }
                if (contains) {

                } else {
                    Countylist.add(String.valueOf(countyCode));
                }


            }
        }
        if (Countylist != null && Countylist.size() > 0) {
            for (String data : Countylist) {
                Map<String, Object> mapdata = new HashMap<>();
                Integer hldatasize = 0;
                Integer hkdatasize = 0;
                Integer dxsegmesize = 0;
                if (maplist != null && maplist.size() > 0) {
                    //分组判断，stream流
                    Map<String, List<Map<String, Object>>> sunmapsSegmentID =
                            maplist.stream().collect(
                                    Collectors.groupingBy(item -> item.get("CountyCode").toString())
                            );
                    List<Map<String, Object>> list = sunmapsSegmentID.get(data);
                    for (Map<String, Object> maplistdata : list) {
                        // Map<String,Object> hkmapdata=new HashMap<>();
                        Object id = maplistdata.get("SegmentID");//断面id
                        Object County = maplistdata.get("County");//区划名称
                        Object CountyCode = maplistdata.get("CountyCode");//区划编码
                        Object segmentCategory = maplistdata.get("SegmentCategory");//断面分类（1河流/2湖库/3地下水）
                        if (segmentCategory != null && !"".equals(segmentCategory)) {
                            if (String.valueOf(segmentCategory).equals("1")) {
                                hldatasize = hldatasize + 1;

                            }
                            if (String.valueOf(segmentCategory).equals("2")) {
                                hkdatasize = hkdatasize + 1;
                            }
                            if (String.valueOf(segmentCategory).equals("3")) {
                                dxsegmesize = dxsegmesize + 1;
                            }
                        }


                    }
                }
                mapdata.put("hldatasize", hldatasize);
                mapdata.put("CountyCode", data);
                mapdata.put("hkdatasize", hkdatasize);
                mapdata.put("dxsegmesize", dxsegmesize);
                segmedata.add(mapdata);
            }
        }
        map.put("hlsegmeid", hlsegmeid);
        map.put("hksegmeid", hksegmeid);
        map.put("segmedata", segmedata);
        map.put("dxsegmeid", dxsegmeid);
        map.put("alllists", alllist);
        return map;
    }

    /**
     * 获取断面对应因子的计算标准
     **/
    public List<Standard> segmentStandardValue(Map map) {
        /*<param name="monitorValue">监测值</param>
                             <param name="standards">标准数据</param>
                             <param name="itemCode">监测项编码</param>*/
        SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//时间格式
        List<Map> list = publicToolsMapper.sectionStandardCalculation(map);
        //断面标准计算进行转换list
        List<Standard> Standardlist = new ArrayList<>();
        if (list != null && list.size() > 0) {
            for (Map s : list) {
                Standard Standard = new Standard();//计算标准实体类
                Object waterType = s.get("WaterType");//水体类型
                Object StartDate = s.get("StartDate");//开始时间
                Object EndDate = s.get("EndDate");//结束时间
                Object ItemCodes = s.get("ItemCode");//监测项编码
                Object Level = s.get("Level");//水质级别
                Object CompareMethod = s.get("CompareMethod");//比对方法（0<= ，1>=，2>，3有或无，4未检出）
                Object StandardValue = s.get("StandardValue");//标准值
                Object Type = s.get("Type");//监测项目标准分类（常规、特殊）
                Object StandardCategory = s.get("StandardCategory");//标准类别（河流/湖库/地下水）
                //下面判读数据不为空进行数据处理到实体类里面
                if (waterType != null && !"".equals(waterType)) {
                    Standard.setWaterType(String.valueOf(waterType));
                } else {
                    Standard.setWaterType("");
                }
                if (StartDate != null && !"".equals(StartDate)) {
                    String StartDateString = String.valueOf(StartDate);
                    Date StartDateStringparse = null;
                    try {
                        StartDateStringparse = dfs.parse(StartDateString);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    Standard.setStartDate(StartDateStringparse);
                }
                if (EndDate != null && !"".equals(EndDate)) {
                    String EndDateString = String.valueOf(EndDate);
                    Date EndDateStringparse = null;
                    try {
                        EndDateStringparse = dfs.parse(EndDateString);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    Standard.setEndDate(EndDateStringparse);
                }
                if (ItemCodes != null && !"".equals(ItemCodes)) {
                    Standard.setItemCode(String.valueOf(ItemCodes));
                } else {
                    Standard.setItemCode("");
                }
                if (Level != null && !"".equals(Level)) {
                    Standard.setLevel(String.valueOf(Level));
                } else {
                    Standard.setLevel("");
                }
                if (StandardValue != null && !"".equals(StandardValue)) {
                    Standard.setStandardValue(String.valueOf(StandardValue));
                } else {
                    Standard.setStandardValue("");
                }
                if (Type != null && !"".equals(Type)) {
                    Standard.setType(String.valueOf(Type));
                } else {
                    Standard.setType("");
                }
                if (StandardCategory != null && !"".equals(StandardCategory)) {
                    Standard.setStandardCategory(String.valueOf(StandardCategory));
                } else {
                    Standard.setStandardCategory("");
                }
                if (CompareMethod != null && !"".equals(CompareMethod)) {
                    Standard.setCompareMethod(String.valueOf(CompareMethod));
                } else {
                    Standard.setCompareMethod("");
                }
                Standardlist.add(Standard);
            }
        }


        return Standardlist;
    }
    /**
     * 根据传参计算集合里面的数据均值
     **/
    public static String avgdata(List<String> data) {
        int size = data.size(); //计算均值的值数量
        BigDecimal datalist = null;
        //Double datalist = null;
        for (String datas : data) {
            BigDecimal dataDouble = BigDecimal.valueOf(Double.valueOf(datas));//获取单个因子转换为可计算的数据格式
            //判断存放值不能为空，为空直接赋值，不为空就进行相加
            if (datalist != null) {
                datalist = datalist.add(dataDouble);
            } else {
                datalist = dataDouble;
            }
        }
        BigDecimal divide = datalist.divide(new BigDecimal(size), 8, BigDecimal.ROUND_HALF_DOWN);
        //number.setScale(6, RoundingMode.HALF_UP)
        return String.valueOf(divide);
    }
    /**
     * 不修约数据
     **/
    public String noriverWaterQualityIndex(List<String> datastring) {
        Double datalist = null;
        for (String data : datastring) {
            Double dataDouble = Double.valueOf(data);//获取单个因子转换为可计算的数据格式
            //判断存放值不能为空，为空直接赋值，不为空就进行相加
            if (datalist != null) {
                datalist = datalist + dataDouble;
            } else {
                datalist = dataDouble;
            }

        }
        //进行四舍六入五成双
        //String data = BankerSRoundingUtils.sciCal(datalist, 4);
        String data = String.valueOf(datalist);
        return data;
    }

    /**
     * 区县水质指数计算
     * @Param [hlIndex 河流水质指数, hlsize 河流数量, hkIndex 湖库水质指数, hksize 湖库数量]
     * （河流的水质指数*河流的数量+湖库的水质指数 *湖库的数量 /(河流的数量+湖库的数量)）
     **/
    public String countyIndex(String hlIndex, Integer hlsize, String hkIndex, Integer hksize) {
        //（河流的水质指数*河流的数量+湖库的水质指数 *湖库的数量 /(河流的数量+湖库的数量)）
        Double v = (Double.valueOf(hlIndex) * hlsize + Double.valueOf(hkIndex) * hksize) / (hlsize + hksize);
        String data = "0";
        if (String.valueOf(v).equals("NaN")) {
            data = "0";
        } else {
            String datav = BankerSRoundingUtils.sciCal(v, 4);
            data = datav;
        }
        return data;

    }

    /**
     * 水源达标状况评估
     * @Param [sldb 水量达标率, syddb 水源达标率]
     **/
    //（水量达标率*0.7+水源达标率*0.3）*100 水源达标状况评估
    public  String assessmentOfWater(Double sldb,Double syddb) {
        double slv =0.0;
        DecimalFormat df = new DecimalFormat("0.00");
        if(sldb!=null&&sldb>0){
            sldb=sldb/100;
            slv = sldb * 0.7;
        }
        double syv =0.0;
        if(syddb!=null&&syddb>0){
            syddb=syddb/100;
            syv = syddb * 0.3;
        }
        double v =  (slv + syv) * 100;;

        return String.valueOf(df.format(v));
    }

    /**
     * 达标状况评估结果
     **/
    public  String assessmentOfWaterresult(Double sldb) {
        String jg="";
        if(sldb>=90){
            jg="优秀";
        }
        if(sldb<90){
            jg="合格";
        }
        if(sldb<60){
            jg="不合格";
        }
        return jg;
    }
}
